package A1_二叉树;

public class LC_110平衡二叉树 {
    public static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(){}
        TreeNode(int val){
            this.val=val;
        }
        TreeNode(int val, TreeNode left, TreeNode right){
            this.val=val;
            this.left=left;
            this.right=right;
        }
    }
    public static void main(String[] args){
        TreeNode root=new TreeNode(3);
        root.left=new TreeNode(9);
        root.right=new TreeNode(20);
//        root.left.left=new TreeNode();
//        root.left.right=new TreeNode();
        root.right.left=new TreeNode(15);
        root.right.right=new TreeNode(7);
        System.out.println(isBalanced(root));
    }
    public static boolean isBalanced(TreeNode root) {
        int result=getHeight(root);
        if(result==-1)
            return false;
        else
            return true;
    }
    public static int getHeight(TreeNode node){
        if(node==null)
            return 0;
        int leftheight=getHeight(node.left);
        if(leftheight==-1)
            return -1;
        int rightheight=getHeight(node.right);
        if(rightheight==-1)
            return -1;
        int result;
        if(Math.abs(leftheight-rightheight)>1)
            result=-1;
        else
            result=1+Math.max(rightheight,leftheight);
        return result;
    }
}
